package com.hyx.api.service.impl.pc_admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hyx.api.domain.*;
import com.hyx.api.domain.bo.RecycleOrderBo;
import com.hyx.api.domain.vo.*;
import com.hyx.api.mapper.*;
import com.hyx.api.service.pc_admin.IRecycleOrderService;
import com.ruoyi.common.core.domain.AjaxResult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 回收订单Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-20
 */
@RequiredArgsConstructor
@Service
public class RecycleOrderServiceImpl implements IRecycleOrderService {
    private final RecycleOrderMapper recycleOrderMapper;
    private final FileUploadMapper uploadMapper;
    private final OfferOrderMapper offerOrderMapper;
    private final RefundOrderMapper refundOrderMapper;
    private final SpreadOrderMapper spreadOrderMapper;
    private final VerifyModelOptionMapper verifyModelOptionMapper;
    private final InquiryOrderMapper inquiryOrderMapper;
    private final RecycleReceivingAddrMapper receivingAddrMapper;
    private final CustomerWithdrawMapper withdrawMapper;

    /**
     * 查询回收订单
     *
     * @param id 回收订单主键
     * @return 回收订单
     */
    @Override
    public RecycleOrderVo selectRecycleOrderById(Long id) {
        //TODO 表以外的字段，写入vo
        return recycleOrderMapper.selectVoById(id);
    }

    @Override
    public List<RecycleOrderVo> queryRecycleOrderList(RecycleOrderBo bo) {
        return recycleOrderMapper.queryPCRecycleOrderList(bo);
    }

    /**
     * 查询回收订单列表
     *
     * @param bo 回收订单
     * @return 回收订单
     */
    @Override
    public List<RecycleOrderVo> selectRecycleOrderList(RecycleOrderBo bo) {
        LambdaQueryWrapper<RecycleOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(ObjectUtils.isNotEmpty(bo.getCode()), RecycleOrder::getCode, bo.getCode());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getInquiryOrderId()), RecycleOrder::getInquiryOrderId, bo.getInquiryOrderId());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getRecycleBusId()), RecycleOrder::getRecycleBusId, bo.getRecycleBusId());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getRecycleOperatorId()), RecycleOrder::getRecycleOperatorId, bo.getRecycleOperatorId());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getPrice()), RecycleOrder::getPrice, bo.getPrice());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getShopId()), RecycleOrder::getShopId, bo.getShopId());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getCompanyId()), RecycleOrder::getCompanyId, bo.getCompanyId());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getOperatorId()), RecycleOrder::getOperatorId, bo.getOperatorId());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getStatus()), RecycleOrder::getStatus, bo.getStatus());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getRecycleTime()), RecycleOrder::getRecycleTime, bo.getRecycleTime());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getShipmentsTime()), RecycleOrder::getShipmentsTime, bo.getShipmentsTime());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getExpressageNo()), RecycleOrder::getExpressageNo, bo.getExpressageNo());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getReceivingTime()), RecycleOrder::getReceivingTime, bo.getReceivingTime());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getIsCatchUp()), RecycleOrder::getIsCatchUp, bo.getIsCatchUp());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getIsRefund()), RecycleOrder::getIsRefund, bo.getIsRefund());
        return recycleOrderMapper.selectVoList(lqw);
    }

    /**
     * 新增回收订单
     *
     * @param bo 回收订单
     * @return 结果
     */
    @Override
    public int insertRecycleOrder(RecycleOrderBo bo) {
        RecycleOrder recycleOrder = tranEntityBeforeSave(bo);
        validEntityBeforeSave(recycleOrder);
        return recycleOrderMapper.insert(recycleOrder);
    }

    /**
     * 修改回收订单
     *
     * @param bo 回收订单
     * @return 结果
     */
    @Override
    public int updateRecycleOrder(RecycleOrderBo bo) {
        RecycleOrder recycleOrder = tranEntityBeforeSave(bo);
        return recycleOrderMapper.updateById(recycleOrder);
    }

    /**
     * 批量删除回收订单
     *
     * @param ids 需要删除的回收订单主键
     * @return 结果
     */
    @Override
    public int deleteRecycleOrderByIds(Long[] ids) {
        return recycleOrderMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(RecycleOrder entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 保存前的数据转换
     */
    private RecycleOrder tranEntityBeforeSave(RecycleOrderBo bo) {
        //TODO 做一些数据转换
        RecycleOrder recycleOrder = new RecycleOrder();
        BeanUtils.copyProperties(bo, recycleOrder);
        return recycleOrder;
    }

    @Override
    public AjaxResult queryRecycleOrderDetail(Long recycleOrderId) {
        InquiryOrderDetailVo resDO = new InquiryOrderDetailVo();
        RecycleOrderVo recycleOrder = recycleOrderMapper.selectVoById(recycleOrderId);
        if (recycleOrder == null) {
            return AjaxResult.error("没有该回收订单，请核实");
        }
        InquiryOrder inquiryOrder = inquiryOrderMapper.selectById(recycleOrder.getInquiryOrderId());
        resDO.setId(inquiryOrder.getId());
        List<FileUpload> files = uploadMapper.selectBatchIds(Arrays.asList(inquiryOrder.getFileIds().split(",")));
        List<String> fileUrls = files.stream().map(FileUpload::getUrl).collect(Collectors.toList());
        resDO.setFileUrls(fileUrls);
        resDO.setRemark(inquiryOrder.getRemark());
        resDO.setModelName(inquiryOrder.getModelName());
        List<VerifyModelOption> modelOptions = verifyModelOptionMapper.selectBatchIds(Arrays.asList(inquiryOrder.getVerifyModelIds().split(",")));
        String specs = modelOptions.stream().filter(s -> s.getType() == 1).map(VerifyModelOption::getName).collect(Collectors.joining(","));
        resDO.setSpecs(specs);
        resDO.setIemi(inquiryOrder.getIemi());
        resDO.setCreateTime(inquiryOrder.getCreateTime());
        OfferOrderVo offerOrderVo = offerOrderMapper.selectVoById(inquiryOrder.getOfferId());
        resDO.setOfferOrderList(Collections.singletonList(offerOrderVo));
        LambdaQueryWrapper<RefundOrder> refundWrapper = Wrappers.lambdaQuery();
        refundWrapper.eq(RefundOrder::getRecycleOrderId, recycleOrderId);
        List<RefundOrderVo> refundOrderVos = refundOrderMapper.selectVoList(refundWrapper);
        if (!refundOrderVos.isEmpty()) {
            recycleOrder.setRefundOrderVo(refundOrderVos);
        }
        LambdaQueryWrapper<SpreadOrder> spreadWrapper = Wrappers.lambdaQuery();
        spreadWrapper.eq(SpreadOrder::getRecycleOrderId, recycleOrderId);
        List<SpreadOrderVo> spreadOrderVos = spreadOrderMapper.selectVoList(spreadWrapper);
        if (!spreadOrderVos.isEmpty()) {
            recycleOrder.setSpreadOrderVo(spreadOrderVos);
        }
        LambdaQueryWrapper<CustomerWithdraw> withdrawWrapper = Wrappers.lambdaQuery();
        withdrawWrapper.eq(CustomerWithdraw::getRecycleOrderId, recycleOrder.getId());
        CustomerWithdraw withdraw = withdrawMapper.selectOne(withdrawWrapper);
        if (withdraw != null) {
            recycleOrder.setCustomerWithdraw(withdraw);
        }
        RecycleReceivingAddr receivingAddr = receivingAddrMapper.selectById(recycleOrder.getReceivingAddrId());
        if (receivingAddr != null) {
            recycleOrder.setReceivingAddr(receivingAddr.getFullAddr());
            recycleOrder.setReceivingName(receivingAddr.getContactName());
            recycleOrder.setReceivingMobile(receivingAddr.getContactMobile());
        }
        resDO.setRecycleOrderVo(recycleOrder);
        return AjaxResult.success(resDO);
    }

    @Override
    public AjaxResult queryRecycleOrderDetailForCode(String code) {
        LambdaQueryWrapper<RecycleOrder> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RecycleOrder::getCode, code);
        List<RecycleOrder> orders = recycleOrderMapper.selectList(wrapper);
        if (orders.isEmpty()) {
            return AjaxResult.error("没有该订单，无法提现，请核实");
        }
        Long recycleOrderId = orders.get(0).getId();
        return queryRecycleOrderDetail(recycleOrderId);
    }

}

